package com.example.cinema.service;

import com.example.cinema.dto.UserDTO;
import com.example.cinema.model.Role;
import com.example.cinema.model.User;
import com.example.cinema.repository.RoleRepository;
import com.example.cinema.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class UserService {

    private final UserRepository userRepository;
    private final RoleRepository roleRepository;

    @Autowired
    public UserService(UserRepository userRepository, RoleRepository roleRepository) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
    }

    // 用户注册
    @Transactional
    public User registerUser(String username, String password, String email) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (userRepository.existsByEmail(email)) {
            throw new RuntimeException("邮箱已被注册");
        }

        // 创建新用户
        User user = new User(username, password, email);
    
        // 默认分配售票员角色
        Role ticketSellerRole = roleRepository.findByName("ROLE_TICKET_SELLER")
                .orElseThrow(() -> new RuntimeException("角色不存在: 售票员"));
        user.setRole(ticketSellerRole);  // 使用一对一关系的setRole
    
        return userRepository.save(user);
    }

    // 用户登录
    public User loginUser(String username, String password) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        if (!user.getPassword().equals(password)) {
            throw new RuntimeException("密码错误");
        }

        return user;
    }

    // 获取所有用户（不包含密码）
    public List<UserDTO> listAllUsers() {
        return userRepository.findAll().stream()
                .map(user -> new UserDTO(user.getId(), user.getUsername(), user.getEmail()))
                .collect(Collectors.toList());
    }

    // 获取用户角色（一对一版本）
    public String getUserRole(String username) {
        Optional<User> userOptional = userRepository.findByUsername(username);
        if (!userOptional.isPresent()) {
            return null;
        }
        User user = userOptional.get();
        Role role = user.getRole();
        return (role != null) ? role.getName() : null;
    }

    // 设置用户角色（一对一版本）
    @Transactional
    public void setUserRole(String username, String roleName) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在: " + username));
    
        Role role = roleRepository.findByName(roleName)
                .orElseThrow(() -> new RuntimeException("角色不存在: " + roleName));
    
        user.setRole(role);
        userRepository.save(user);
    }
}